package com.upcode.weighing.redisson.service.impl;


import com.upcode.weighing.redisson.service.DistributedLocker;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

/**
 * @date 2021/6/6
 */
public class DistributedLockerImpl implements DistributedLocker {

    private RedissonClient redissonClient;

    /**
     * 加锁
     *
     * @param lockKey 锁名称
     * @return
     */
    @Override
    public RLock lock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock();
        return lock;
    }

    /**
     * 加锁
     *
     * @param lockKey 锁名称
     * @param timeout 锁有效时间
     * @return
     */
    @Override
    public RLock lock(String lockKey, int timeout) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(timeout, TimeUnit.SECONDS);
        return lock;
    }

    /**
     * 加锁
     *
     * @param lockKey 锁名称
     * @param unit    时间单位
     * @param timeout 锁有效时间
     * @return
     */
    @Override
    public RLock lock(String lockKey, TimeUnit unit, int timeout) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(timeout, unit);
        return lock;
    }

    /**
     * 尝试性加锁
     *
     * @param lockKey   锁名称
     * @param unit      时间单位
     * @param waitTime  等待时间
     * @param leaseTime 续租时间
     * @return
     */
    @Override
    public boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime) {
        RLock lock = redissonClient.getLock(lockKey);
        try {
            return lock.tryLock(waitTime, leaseTime, unit);
        } catch (InterruptedException e) {
            return false;
        }
    }

    /**
     * 根据锁名称解锁
     *
     * @param lockKey
     */
    @Override
    public void unlock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.unlock();
    }

    /**
     * 根据锁对象解锁
     *
     * @param lock
     */
    @Override
    public void unlock(RLock lock) {
        lock.unlock();
    }

    /**
     * redisson客户端连接
     * @param redissonClient
     */
    @Override
    public void setRedissonClient(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }
}
